const router = require('koa-router')()
const svgCaptcha = require('svg-captcha');
const jwt = require("jsonwebtoken");
const uuid = require('uuid');
const users = [];
const fs = require('fs');
const koaBody = require('koa-body')
const db = require('../db/db.js');
const path = require("path");
const formidable = require('formidable');
const json = require('koa-json');
const dirPath = path.join(path.resolve(__dirname, '../'), '/public/images')

router.get('/', async (ctx, next) => {
  ctx.body = 'Hello Koa 2!'
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

//登陆认证
const myKey = "131415"
const token = jwt.sign({
  exp: Math.floor(Date.now() / 1000) + (60 * 60),
  data: 'foobar',
  username: 'zhangsan',
  pwd: 12345
}, myKey);
//console.log(token);

jwt.verify(token, myKey, function (err, decoded) {
  //console.log(decoded) // bar
});

router.post("/token", async (ctx, next) => {
  let body = JSON.parse(ctx.request.body);
  let username = body.username;
  let pwd = body.password;
  //let code = body.code
  if (username == "zhangsan" && pwd == "12345") {
    console.log(username, pwd)
    let token = jwt.sign({ username: "zhangsan", pwd: "12345" }, myKey);
    ctx.body = { token: token };//响应
    //console.log(token)
  }
})


router.get('/captcha', async (ctx, next) => {
  var captcha = svgCaptcha.create();
  let img = captcha.data;
  ctx.session.captcha = captcha.text;
  ctx.body = `<a href="javascript: window.location.reload();">${img}</a>`;
})


router.post('/login', async (ctx, next) => {
  let b = ctx.request.body;
  const insertSql = 'INSERT INTO login (username, pwd) VALUES (?, ?)';
  if (b.username == 'zhangsan' && b.pwd == '12345') {
    await ctx.db.query(insertSql, [b.username, b.pwd]);
    ctx.body = { "code": 200, "msg": "success" };//向前端响应，前端控制台不会显示404
  } else {
    ctx.body = { "code": 404, "msg": "fail" };
  }
})


//用户管理
router.get('/users', (ctx, next) => {
  ctx.body = users;
});

router.get('/users/:id', (ctx, next) => {
  const id = ctx.params.id;
  const user = users.find(u => u.id === id);
  if (!user) {
    ctx.status = 404;
    ctx.body = `User with id ${id} not found`;
    return;
  }
  ctx.body = user;
});

router.post('/users', (ctx, next) => {
  const user = ctx.request.body;
  if (!user.name) {
    ctx.status = 400;
    ctx.body = 'Name is required';
    return;
  }
  user.id = uuid.v4();
  user.createTime = new Date();
  user.updateTime = user.createTime;
  users.push(user);
  ctx.status = 201;
  const insertsql = 'INSERT INTO manager (id,name,phone,email,address) VALUES (?,?,?,?,?)'
  ctx.db.query(insertsql,[user.id,user.name,user.phone,user.email,user.address])
  ctx.body = user;
});

router.put('/users/:id', (ctx, next) => {
  const Id = ctx.params.id;
  const user = users.find(u => u.id === Id);
  if (!user) {
    ctx.status = 404;
    ctx.body = `User with id ${Id} not found`;
    return;
  }
  const updates = ctx.request.body;
  user.name = updates.name || user.name;
  user.phone = updates.phone || user.phone;
  user.email = updates.email || user.email;
  user.address = updates.address || user.address;
  user.updateTime = new Date();
  const Name = user.name;
  const Phone = user.phone;
  const Email = user.email;
  const Address= user.address;
  
 const updateSql = 'UPDATE manager SET name=Name,phone=Phone,email=Email,address=Address where id=Id'
 ctx.db.query(updateSql,[Id,Name,Phone,Email,Address])
  ctx.body = user;
});

router.delete('/users/:id', (ctx, next) => {
  const Id = ctx.params.id;
  const index = users.findIndex(u => u.id === Id);
  if (index === -1) {
    ctx.status = 404;
    ctx.body = `User with id ${Id} not found`;
    return;
  }
  users.splice(index, 1);
  ctx.status = 204;
  const deletesql ='DELETE FROM manager where id = Id'
  ctx.db.query(deletesql,[Id])
  ctx.body = null;
});


router.post('/upload', async (ctx, next) => {
  let updirPath = path.join(__dirname, '../uploads');
  const insertsql = 'INSERT INTO images (name,size,type,url) values(?,?,?,?)'
  let form = formidable({
    multiples: true,
    uploadDir: updirPath,
    keepExtensions: true
  })
  form.parse(ctx.req, async (err, fields, files) => {
    if (err) {
      console.log(err);
    }
    let img = JSON.stringify(files);
    let imgs = JSON.parse(img).file;
    console.log(imgs)
    await ctx.db.query(insertsql,[imgs.newFilename,imgs.size,imgs.mimetype,imgs.filepath])
  })
  ctx.body = form;
  //console.log(form);

});

router.get('/imgList/:name', (ctx, next) => {
  const imageName = ctx.params.name
  ctx.body = fs.readFileSync('./uploads/' + imageName)
})  
router.get('/imgList', (ctx, next) => {
  const path = './uploads/'
  let imgsList = []
  let size = ''
  fs.readdirSync(path).forEach(files => {
    const buffer = fs.readFileSync(path + files);
    const magicNumber = buffer.toString('hex', 0, 4);
    let type;
    switch (magicNumber) {
      case '89504e47':
        type = 'PNG';
        break;
      case '47494638':
        type = 'GIF';
        break;
      case 'ffd8ffe0':
      case 'ffd8ffe1':
      case 'ffd8ffe2':
        type = 'JPEG';
        break;
      default:
        type = 'unknown';
    }
    const imgsFiles = path + files
    const stat = fs.statSync(imgsFiles)
    const url = fs.readFileSync(imgsFiles)
    size = stat.size
    size = size / 1024 + 'KB'
    let imageFilePath = path + files;
    let imgList = fs.readFileSync(imageFilePath).toString('base64');
    imgsList.push({
      name: files,
      data: imgList,
      size: size,
      type: type,
      url: url
    })
  }
  )
  imgsList = JSON.stringify(imgsList)
  ctx.body = imgsList
})
router.post('/deleteImage', async (ctx, next) => {
  const { fileName } = ctx.request.body; // 获取要删除的文件名
  const Name = fileName;
  const deletesql ='DELETE FROM images where name = Name'
  try {
    // 执行删除操作
    fs.unlink(`./uploads/${fileName}`, (err) => {
      if (err)
        throw err;
      console.log(`${fileName} has been deleted.`);
    });
    ctx.db.query(deletesql,[Name])
    // 返回成功响应
    ctx.body = {
      success: true,
      message: 'File has been deleted.',
    };
  } catch (err) {
    // 返回失败响应
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: 'Failed to delete file.',
      error: err.message,
    };
  }
})
//物流管理系统
// 模拟数据，初始化物流线路列表
const data = [
  {
    id: 1,
    route: '北京-上海',
    path: '北京、天津、济南、上海',
    tel: '010-1234567',
    address: '北京市海淀区',
    top: false,
  },
  {
    id: 2,
    route: '北京-广州',
    path: '北京、武汉、广州',
    tel: '010-2345678',
    address: '北京市朝阳区',
    top: false,
  },
  {
    id: 3,
    route: '上海-广州',
    path: '上海、合肥、南昌、广州',
    tel: '021-3456789',
    address: '上海市黄浦区',
    top: false,
  },
]

let id = data.length

router.get('/data', async (ctx, next) => {
  const currentPage = parseInt(ctx.query.currentPage) || 1
  const pageSize = parseInt(ctx.query.pageSize) || 5
  const search = ctx.query.search || ''
  let list = data.filter(item => item.route.indexOf(search) > -1)
  const total = list.length
  list = list.slice((currentPage - 1) * pageSize, currentPage * pageSize)
  ctx.body = {
    list,
    total,
  }
})

router.post('/save', async (ctx, next) => {
  const body = ctx.request.body
  id++
  body.id = id
  body.top = false
  data.push(body)
  const insertSql = 'INSERT INTO thing (id,route,path,tel,address) VALUES (?,?,?,?,?)';
  await ctx.db.query(insertSql,[body.id,body.route,body.path,body.tel,body.address])
  ctx.body = {
    message: '添加成功！',
  }
})

router.put('/save', async (ctx, next) => {
  const body = ctx.request.body
  const ID = ctx.request.body.id;
  const Route =ctx.request.body.route;
  const Path = ctx.request.body.path;
  const Tel =ctx.request.body.tel;
  const Address=ctx.request.body.address;
  const index = data.findIndex(item => item.id === body.id)
  if (index > -1) {
    data.splice(index, 1, body)
    const updateSql = 'UPDATE thing SET route=Route,path=Path,tel=Tel,address=Address where id=ID'
    await ctx.db.query(updateSql,[ID,Route,Path,Tel,Address])
    ctx.body = {
      message: '编辑成功！',
    }
  } else {
    ctx.body = {
      message: '编辑失败，数据不存在！',
    }
  }
})

router.delete('/remove/:id', async (ctx, next) => {
  const Id = parseInt(ctx.params.id)
  const index = data.findIndex(item => item.id === Id)
  if (index > -1) {
    data.splice(index, 1)
    const deletesql ='DELETE FROM thing where id = Id'
    await ctx.db.query(deletesql,[Id])
    ctx.body = {
      message: '删除成功！',
    }
  } else {
    ctx.body = {
      message: '删除失败，数据不存在！',
    }
  }
})

router.put('/top', async (ctx, next) => {
  const body = ctx.request.body
  const index = data.findIndex(item => item.id === body.id)
  if (index > -1) {
    data[index].top = true
    ctx.body = {
      message: '置顶成功！',
    }
  } else {
    ctx.body = {
      message: '置顶失败，数据不存在！',
    }
  }
})

module.exports = router
